package com.xuecheng.manage_cms_client.mq;

import com.alibaba.fastjson.JSON;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.manage_cms_client.dao.CmsPageRepository;
import com.xuecheng.manage_cms_client.dao.CmsSiteRepository;
import com.xuecheng.manage_cms_client.service.PageService;
import org.apache.logging.log4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * 消费者客户端,用于监听页面发布队列消息,接受到消息后从monagedb中下载文件
 *
 */
@Component
public class ConsumerPostPage {
    private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(ConsumerPostPage.class);
    @Autowired
    CmsPageRepository cmsPageRepository;
    @Autowired
    PageService pageService;

    @RabbitListener(queues = {"xuecheng.mq.queue"})
    public void postPage(String msg){
        //解析信息
        Map map = JSON.parseObject(msg,Map.class);
        LOGGER.info("receive cms post page: {}",msg.toString());
        //取出页面id
        String pageId  = (String) map.get("pageId");
        //查询页面信息
        Optional<CmsPage> optional = cmsPageRepository.findById(pageId);
        if(!optional.isPresent()){
            LOGGER.info("receive cms post cmsPage is null: {}",msg.toString());
            return;

        }
        pageService.savePageToServerPath(pageId);

    }
}
